package cn.ipenta.jkb.service;

import java.util.List;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.ipenta.jkb.JkbServiceException;
import cn.ipenta.jkb.entity.ChildInfo;
import cn.ipenta.jkb.entity.Healer;
import cn.ipenta.jkb.entity.Regulator;
import cn.ipenta.jkb.entity.TxInfo;
import cn.ipenta.jkb.repository.ChildInfoBlockChainSource;
import cn.ipenta.jkb.repository.ChildInfoRepository;
import cn.ipenta.jkb.repository.HealerRepository;
import cn.ipenta.jkb.repository.RegulatorRepository;
import cn.ipenta.jkb.repository.TxInfoRepository;

@Service
public class CustomerService extends AbstractTxService {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(CustomerService.class);

	@Autowired
	ChildInfoBlockChainSource childInfoBlockChainSource;

	@Autowired
	RegulatorRepository regulatorRepository;

	@Autowired
	HealerRepository healerRepository;

	@Autowired
	ChildInfoRepository childInfoRepository;

	@Autowired
	TxInfoRepository txInfoRepository;
	
	@Autowired
	MongoTemplate mongoTemplate;
	

	// ******新版******/、	

	public Boolean checkChildAndApply(ChildInfo childInfo, TxInfo txInfo) throws JkbServiceException {

		Boolean isCreated = Boolean.FALSE;

		String childhash = findChildInfo(childInfo);
		if (childhash != null) {
			if (createApply(childhash, txInfo)) {
				isCreated = Boolean.TRUE;
			}
		}

		return isCreated;
	}

	/**
	 * @param childhash
	 * @param txInfo
	 * @return
	 */
	public boolean createApply(String childhash, TxInfo txInfo) {
		Boolean isCreated = Boolean.FALSE;
		
		TxInfo reqtxInfo =  new TxInfo();
		reqtxInfo.setInfo(childhash);
		reqtxInfo.setType(txInfo.getType());
		
		if (!txInfoRepository.exists(Example.of(reqtxInfo))) {
			txInfo.setInfo(childhash);
			TxInfo entity = txInfoRepository.save(txInfo);
			if (entity != null) {
				isCreated = Boolean.TRUE;
				String[] txhashAndtime = txInfoBlockChainSource.createInBack(entity).split(",");
				entity.setTxhash(txhashAndtime[0]);
				entity.setTime(txhashAndtime[1]);
				txInfoRepository.save(entity);
			}
		} else {
			throw new JkbServiceException("交易存证已经存在");
		}
		return isCreated;
	}
	

	public String findChildInfo(ChildInfo childInfo) {

		ChildInfo entity = null;

		if (childInfoRepository.exists(Example.of(childInfo))) {
			entity = childInfoRepository.findOne(Example.of(childInfo));
			logger.debug("101,{}",JSON.toJSON(entity));
		} else {
			entity = childInfoRepository.save(childInfo);
		}
		if (entity != null) {
			return entity.getId();
		}
		return null;
	}

	// **********旧版**********//
	public Boolean checkAndApply(ChildInfo childInfo, TxInfo txInfo) throws JkbServiceException {

		Boolean isCreated = Boolean.FALSE;

		// 判断是否有记录，没有注册孩子的信息，然后依据病例信息
		String childhash = checkAndregisterChildRecord(childInfo);
		if (childhash != null) {
			logger.debug("33:{}", JSON.toJSON(childInfo));
			if (createApplyRecord(childhash, txInfo)) {
				isCreated = Boolean.TRUE;
			}
		}
		return isCreated;
	}

	public String checkAndregisterChildRecord(ChildInfo childInfo) {

		if (hasChildRecord(childInfo)) {
			return findChildRecord(childInfo).getId();
		} else {
			ChildInfo entity = createChildRecord(childInfo);
			if (entity != null && entity.getId() != null) {
				return entity.getId();
			}
		}
		return null;
	}

	public Boolean hasChildRecord(ChildInfo childInfo) {
		return childInfoBlockChainSource.has(childInfo);
	}

	public ChildInfo createChildRecord(ChildInfo childInfo) {
		logger.debug("62{}", JSON.toJSON(childInfo));
		return childInfoBlockChainSource.create(childInfo);
	}

	public Boolean createApplyRecord(String childhash, TxInfo txInfo) {
		if (!txInfoBlockChainSource.has(txInfo)) {
			txInfo.setInfo(childhash);
			TxInfo entity = txInfoBlockChainSource.create(txInfo);
			return entity != null;
		} else {
			throw new JkbServiceException("交易存证已经存在");
		}
	}

	public ChildInfo findChildRecord(ChildInfo childInfo) {
		return childInfoBlockChainSource.findInLocal(childInfo);
	}

	public List<Regulator> findRegulatorsAll() {
		return regulatorRepository.findAll();
	}

	public List<Healer> findHealersAll() {
		return healerRepository.findAll();
	}

	public List<TxInfo> findTxRecordByIdAndOrderAndSort(String id,String order,String sortBy) {
		

		Query query = new Query(new Criteria().orOperator(Criteria.where("senderId").is(id),Criteria.where("receiverId").is(id)));
		
		if(order != null && sortBy != null){  
	        query.with(new Sort(new Sort.Order(order.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sortBy)));  
	    }else {  
	        query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "type")));  
	    }

		return mongoTemplate.find(query, TxInfo.class);
	}

}
